package org.lzuploader.gui;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Shell;

/** Class used to manage the position of some elements when they are created.
 * 
 * @author Emmanuel Cron
 *
 */
public final class Position
{
    /** Logger of this class. */
    private static Log log = LogFactory.getLog(Position.class);
    
    /** User should never instantiate this class.
     * 
     */
    private Position()
    {
        throw new UnsupportedOperationException();
    }
    
    /** Centers a shell on a given parent shell, and checks if the window is correctly placed on the screen.
     * 
     * @param parent Parent shell
     * @param shell Shell of the window to center
     * @param width Width of the shell to center
     * @param height Height of the shell to center
     */
    public static void centerElement(final Shell parent, final Shell shell, final int width, final int height)
    {
        log.debug("Centering " + shell.toString() + " element on " + parent.toString() + " (width = " + width + ", height = " + height + ").");
        
        final Point location = parent.getLocation();
        final Point size = parent.getSize();
        int x = location.x + size.x / 2 - width / 2;
        int y = location.y + size.y / 2 - height / 2;
        
        log.trace("Checking window position.");
        
        if (x < 0)
        {
            x = 10;
        }
        else if (x + width > parent.getDisplay().getClientArea().width)
        {
            x = parent.getDisplay().getClientArea().width - width - 10;
        }
        
        if (y < 0)
        {
            y = 10;
        }
        else if (y + height > parent.getDisplay().getClientArea().height)
        {
            y = parent.getDisplay().getClientArea().height - height - 10;
        }
        
        shell.setLocation(
             x,
             y
        );
        shell.setSize(width, height);
    }
}
